import { defineEventHandler, readBody } from "h3";
import { createUser, checkEmailExists, checkUsernameExists } from "../../database/services/userService";
import { verifyCode } from "../../services/verificationService";
import { emailService } from "../../utils/emailService";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);

    // 数据验证
    if (!body.username || !body.password || !body.email) {
      throw new Error("用户名、密码和邮箱不能为空");
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(body.email)) {
      throw new Error("邮箱格式不正确");
    }

    // 验证验证码
    if (!body.verificationCode) {
      throw new Error("验证码不能为空");
    }

    const verificationResult = verifyCode(body.email, body.verificationCode);
    console.log(verificationResult, "verificationResult", body);

    if (!verificationResult.success) {
      return {
        success: false,
        error: verificationResult.message,
      };
    }

    // 检查邮箱是否已存在
    const emailExists = await checkEmailExists(body.email);
    if (emailExists) {
      return {
        success: false,
        error: "该邮箱已被注册，请使用其他邮箱",
      };
    }

    // 检查用户名是否已存在
    const usernameExists = await checkUsernameExists(body.username);
    if (usernameExists) {
      return {
        success: false,
        error: "该用户名已被使用，请选择其他用户名",
      };
    }

    // 创建用户数据（不包含验证码）
    const userData = {
      username: body.username,
      password: body.password,
      email: body.email,
      name: body.name || body.username, // 如果没有提供姓名，使用用户名
      authority: body.authority || 1, // 默认权限为1
    };

    // 使用中间件中创建的事务（可选）
    console.log("准备创建用户:", userData);
    const newUser = await createUser(userData);
    console.log("用户创建成功:", newUser);

    // 发送注册成功邮件（异步，不阻塞响应）
    emailService
      .sendRegistrationSuccess(userData.email, userData.username)
      .then((result) => {
        if (result.success) {
          console.log("注册成功邮件发送成功");
        } else {
          console.error("注册成功邮件发送失败:", result.error);
        }
      })
      .catch((error) => {
        console.error("发送注册成功邮件时出错:", error);
      });

    return {
      success: true,
      data: newUser,
      message: "注册成功",
    };
  } catch (error) {
    console.error("注册用户时出错:", error);

    return {
      success: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
});
